// pages/bag/bag.js
var bagUtil = require("../../utils/bagUtil");
Page({
  data:{
    placeDone: false, // 是否下单成功
    bagList: [],
    skuObj: {}, // skuObj
    productObj: {},
    isCheckAll: false,
    checkNum: 0, // 选择商品类别数量
    checkIds: {}, //选择的商品 productid_typeid : num
    startX: 0, //开始x坐标
    startY: 0, //开始y坐标

    hideNumOp: true,
    changeNum: 0, // 修改数量
    changeId : 0, // 待修改编号

    placeOrdering: false, // 是否在提交订单中
    placeOrderId : '', // 订单号
  },
  onLoad:function(options){
    
  },
  onShow:function(){
    // 页面显示
    var that = this;
    this.setData({
      bagList: bagUtil.listBag(this),
      placeDone: false,
      isCheckAll: false,
      checkNum: 0,
      checkIds: {}
    });
  },
  touchstart: function(e){
    //开始滑动
    this.data.bagList.forEach(function(v, i){
      if(v.isTouchMove){
        v.isTouchMove = false;
      }
    });
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      bagList: this.data.bagList
    });
  },
  touchmove: function(e){
    var that = this,
    index = e.currentTarget.dataset.index, // 当前索引
    startX = that.data.startX,
    startY = that.data.startY,
    touchMoveX = e.changedTouches[0].clientX,
    touchMoveY = e.changedTouches[0].clientY,
    angle = that.angle({X:startX, Y:startY}, {X:touchMoveX, Y:touchMoveY});

    that.data.bagList.forEach(function(v, i){
      v.isTouchMove = false;
      if(Math.abs(angle) > 30) return;
      if(i == index){
        if(touchMoveX > startX){
          // 右滑
          v.isTouchMove = false;
        }else{
          // 左滑
          v.isTouchMove = true;
        }
      }
    });

    that.setData({
      bagList : that.data.bagList
    });
  },
  angle: function(start, end){
    var _X = end.X - start.X,
    _Y = end.Y - start.Y;

    return 360 * Math.atan(_Y/_X) / (2 * Math.PI);
  },
  del: function(e){
    var that = this;
    var item = this.data.bagList[e.currentTarget.dataset.index];
    bagUtil.delBag(item.id, function(){
      that.data.bagList.splice(e.currentTarget.dataset.index, 1);
      // 需要从已经选择的里面删除
      if(that.data.checkIds[item.id]){
        // 如果已经选择了
        delete that.data.checkIds[item.id];
        that.data.checkNum--;
        if(that.data.checkNum == that.data.bagList.length) that.data.isCheckAll = true;
      }
      that.setData({
        bagList: that.data.bagList,
        isCheckAll: that.data.isCheckAll,
        checkIds: that.data.checkIds,
        checkNum: that.data.checkNum
      });
    });
  },
  selectOne: function(e){
    // 选择某一条目
    var id = e.currentTarget.dataset.id;
    var num = e.currentTarget.dataset.num;
    if(this.data.checkIds[id]){
      // 如果已经选择，取消选择
      delete this.data.checkIds[id];
      this.data.checkNum = this.data.checkNum - 1;
      this.setData({
        isCheckAll: false,
        checkIds: this.data.checkIds,
        checkNum: this.data.checkNum
      });
    }else{
      // 选中,需要判断
      this.data.checkIds[id] = num;
      console.log(this.data.checkIds);
      this.data.checkNum++;
      var checkAll = this.data.checkNum == this.data.bagList.length;
      
      this.setData({
        isCheckAll: checkAll,
        checkIds: this.data.checkIds,
        checkNum: this.data.checkNum
      });
    }
  },
  selectAll: function(){
    // 选择所有条目
    if(this.data.isCheckAll){
      this.setData({
        isCheckAll: false,
        checkIds: {},
        checkNum: 0
      });
    }else{
      var checkNum = 0;
      var checkIds = {};
      for(var i = 0; i< this.data.bagList.length; i++){
        checkNum++;
        checkIds[this.data.bagList[i].id] = this.data.bagList[i].response.quantity;
      }
      this.setData({
        isCheckAll: true,
        checkIds: checkIds,
        checkNum: checkNum
      });
    }
    
  },
  changeNum: function(e){
    var id = e.currentTarget.dataset.id;
    var num = e.currentTarget.dataset.num;
    var parentId = e.currentTarget.dataset.parentid;
    if(parseInt(parentId) > 0) return;

    this.setData({hideNumOp: false, changeNum: num, changeId: id});
  },
  changeNumSubmit: function(){
    // 修改数量
    var that = this;
    bagUtil.updateBag(this.data.changeId, this.data.changeNum, function(result){
      if(result){
        for(var i = 0; i < that.data.bagList.length; i++){
          if(that.data.bagList[i].id == that.data.changeId){
            that.data.bagList[i].response.quantity = that.data.changeNum;
            break;
          }
        }

        if(that.data.checkIds[that.data.changeId]){
          that.data.checkIds[that.data.changeId] = that.data.changeNum;
        }

        that.setData({
          bagList: that.data.bagList,
          checkIds: that.data.checkIds,
          changeId: '',
          changeNum: 0,
          hideNumOp: true
        });
      }else{
        wx.showModal({
            title: '提示',
            content: '修改失败',
            showCancel: false,
            confirmColor: '#111111',
            success: function(res){console.log(res)},
            fail: function(e){console.log(e);}
        });
      }  
    }); 
  },
  numDown: function(){
    if(this.data.changeNum == 1) return;
    var changeNum = this.data.changeNum - 1;
    this.setData({changeNum: changeNum});
  },
  numUp: function(){
    this.setData({changeNum: parseInt(this.data.changeNum)+1});
  },
  hideMask: function(){
    this.setData({hideNumOp: true, changeNum: 0, changeId: ''});
  },

  placeOrder: function(){
    // 下订单
    if(!getApp().globalData.userInfo.userId) return;

    var that = this;
    let objects = {
      tableID: getApp().globalData.TABLE_ID_ADDRESS_BOOK,
      created_by: getApp().globalData.userInfo.userId,
      limit: 1,
      offset: 0
    };
    wx.BaaS.getRecordList(objects).then( (res) => {
      // success
      if(res.data.objects.length>0 && res.data.objects[0].response.status=='valid'){
        // 存在信息 并且 认证过了 可以下单了
        // 组合选择的物品
        var address_book_id = res.data.objects[0].id;
        var orderArr = [];
        var orderItems = [];
        var orderSnapshot = {};
        for(var i = 0; i < that.data.bagList.length; i++){
          if(this.data.checkIds[that.data.bagList[i].id]){
              orderArr.push({"product_sku_id": that.data.bagList[i].response.product_sku_id, "quantity": that.data.bagList[i].response.quantity});
              if (typeof orderSnapshot[that.data.bagList[i].response.product_sku_id] == 'undefined'){
                orderSnapshot[that.data.bagList[i].response.product_sku_id] = {
                  skuId: that.data.bagList[i].response.product_sku_id,
                  skuTitle: that.data.skuObj[that.data.bagList[i].response.product_sku_id].title,
                  quantity: that.data.bagList[i].response.quantity,
                  productId: that.data.skuObj[that.data.bagList[i].response.product_sku_id].product_id,
                  productTitle: that.data.productObj[that.data.skuObj[that.data.bagList[i].response.product_sku_id].product_id].title,
                  productImage: that.data.productObj[that.data.skuObj[that.data.bagList[i].response.product_sku_id].product_id].images[0]
                };
              }
          }
        }

        if(orderArr.length < 1) return;

        orderArr.forEach((attr) => {

          let tableID = getApp().globalData.TABLE_ID_ORDER_ITEM;
          let data = {
            "product_sku_id": attr.product_sku_id,
            "quantity": attr.quantity
          }
          let objects = {
             tableID,
             data
          }

          wx.BaaS.createRecord(objects).then( (res) => {
            orderItems.push(res.data.id);

            if (orderItems.length == Object.keys(that.data.checkIds).length) {
              // order_item表添加完成
              // TODO 组合订单显示快照信息
              let tableID = getApp().globalData.TABLE_ID_ORDER;
              let data = {
                "order_items": orderItems,
                "address_book_id": address_book_id,
                "status": "pending",
                "snapshot": JSON.stringify(orderSnapshot)
              };
              let objects = {
                tableID,
                data
              };
              wx.BaaS.createRecord(objects).then((res) => {
                // success
                for (var i = 0; i < that.data.bagList.length; i++) {
                  if (that.data.checkIds[that.data.bagList[i].id]) {
                    bagUtil.delBag(that.data.bagList[i].id, function () {
                      delete that.data.bagList[i];
                    });
                  }
                }

                that.setData({
                  checkIds: {},
                  bagList: that.data.bagList,
                  checkNum: 0,
                  placeOrderId: that.data.placeOrderId,
                  placeOrdering: that.data.placeOrdering,
                  placeDone: true
                });
              }, (err) => {
                // err
              });
            }
          })

        })

      }else{
        wx.showModal({
          title: '提示',
          content: '请至「我的资料」认证成功后，即可下单。',
          showCancel: false,
          confirmText: '确认',
          confirmColor: '#111111',
          success: function(res){
          },
          fail: function(){}
        });
      }
    }, (err) => {
      // err
    });
    return false;
    // TODO 验证用户是否已经实名认
    // if(getApp().){

    // }
    if(this.data.checkNum > 0){
      this.data.placeOrdering = true;
      bagUtil.placeOrder(this.data.checkIds, function(res){
        if(res.result){
          // 如果已经成功了
          this.data.placeOrderId = res.orderid;
          this.data.placeOrdering = false;
          // 需要将购物车剔除
          for(var i = 0; i < this.data.bagList.length; i++){
            if(this.data.checkIds[this.data.bagList[i].id]){
              var tmpArr = 
              delete this.data.bagList[i];
              bagUtil.delBag(this.data.bagList[i].productId, this.data.bagList[i].typeId);
            }
          }

          this.data.setData({
            checkIds: {},
            bagList: this.data.bagList,
            checkNum: 0,
            placeOrderId: this.data.placeOrderId,
            placeOrdering: this.data.placeOrdering,
            placeDone: true
          });
        }  
      }, function(){

      });
    }
  },
  goHome: function(){
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  goMy: function(){
    // 渠道我的页面
    wx.switchTab({
      url: '/pages/my/my'
    })
  }
})